package facebook;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.google.code.facebookapi.FacebookJaxbRestClient;
import com.google.code.facebookapi.FacebookWebappHelper;

public class FacebookUserFilter implements Filter {

    private static final String api_key = "672c814ee3de3c59ed6434a6bbf190d8";
    private static final String secret = "65246ca3141547f064aa1f7d3df217cc";
    private static final String FACEBOOK_USER_CLIENT = "facebook.user.client";
    
    public void init(FilterConfig filterConfig) throws ServletException {}

    public void destroy() {}

    public void doFilter(ServletRequest req, ServletResponse res,
    		FilterChain chain) throws IOException, ServletException {
    	
    	HttpServletRequest request = (HttpServletRequest) req;
    	HttpServletResponse response = (HttpServletResponse) res;

    	HttpSession session = request.getSession(true);

    	FacebookJaxbRestClient userClient = getUserClientJaxb(session);
    	if (userClient == null) {
    		userClient = new FacebookJaxbRestClient(api_key, secret);
    		session.setAttribute(FACEBOOK_USER_CLIENT, userClient);
    	}

    	FacebookWebappHelper<?> facebook = new FacebookWebappHelper<Object>(
    			request, response, api_key, secret, userClient);
    	String nextPage = request.getRequestURI();
    	nextPage = nextPage.substring(nextPage.indexOf("/", 1) + 1); 

    	boolean redirectOccurred = facebook.requireLogin(nextPage);
    	if (redirectOccurred) {
    		return;
    	}
    	redirectOccurred = facebook.requireFrame(nextPage);
    	if (redirectOccurred) {
    		return;
    	}

    	chain.doFilter(request, response);
    }

    public static FacebookJaxbRestClient getUserClientJaxb(HttpSession session) {
        return (FacebookJaxbRestClient)session.getAttribute(FACEBOOK_USER_CLIENT);
    }
}